﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Storage;

namespace SharpShare.Afp.Protocol.Handlers {
    internal class AfpCopyFileRequestHandler : IAfpRequestHandler {
        #region IAfpRequestHandler Members

        public byte CommandCode {
            get { return 5; }
        }

        public AfpResultCode Process(IAfpSession session, DsiHeader dsiHeader, AfpStream requestStream, AfpStream responseStream) {
            requestStream.ReadPadding();

            ushort sourceVolumeId = requestStream.ReadUInt16();
            uint sourceDirectoryId = requestStream.ReadUInt32();
            ushort destinationVolumeId = requestStream.ReadUInt16();
            uint destinationDirectoryId = requestStream.ReadUInt32();

            IAfpVolume sourceVolume;
            IStorageFile sourceFile = requestStream
                .ReadPathAndFind(session, sourceVolumeId, sourceDirectoryId, out sourceVolume)
                .DemandFile();

            IAfpVolume destinationVolume;
            IStorageContainer destinationContainer = requestStream
                .ReadPathAndFind(session, destinationVolumeId, destinationDirectoryId, out destinationVolume)
                .DemandContainer();

            string newName = requestStream.ReadPath().FirstOrDefault();

            sourceFile.Copy(destinationContainer, newName);

            return AfpResultCode.FPNoErr;
        }

        #endregion
    }
}
